<?php 
namespace Emos\Field;

use Emos\Common;

class Image extends File {   
    var $nullable = true;
    protected $versions = array();

    protected $validExtensions = array('png', 'gif', 'jpg', 'jpeg');

    public function __construct() {
        $this->docRoot = $_SERVER['DOCUMENT_ROOT'];      
    }    
    
    public function addVersion($width=null, $height=null, $prefix=null, $method='inscribe') {           
        if($prefix === null) {
            $prefix = '/var/'.$this->dbName.'-'.count($this->versions).'-';
        }        
        if($width === null)  { $width = 10000;  }
        if($height === null) { $height = 10000; }
        
        $this->versions[] = array(
            'width'  => $width,
            'height' => $height, 
            'prefix' => $prefix, 
            'method' => $method
        );
        
        return $this;
    }
    
    public function html() {        
        $html = '';

        $html .= "<input type='file' name='{$this->htmlName}' value='' />";
        
        if($this->value && count($this->versions) > 0) {                        
            $ext = '?';
            if(preg_match('/  \. ([a-z0-9]{1,7})  $  /xi', $this->value, $m)) {
                $ext = strtoupper($m[1]);            
            }    
            
            $title = $ext;
            foreach($this->versions as $version) {
                $size = ceil(@filesize("{$this->docRoot}{$version['prefix']}{$this->value}") / 1024);
                @list($w, $h) = getimagesize("{$this->docRoot}{$version['prefix']}{$this->value}");                 
                                
                $title .= Common::plain(", {$w}x{$h} {$size}KB");                
            }   
            
            $version = $this->versions[0];
            $firstUrl = Common::plain("{$this->urlRoot}{$version['prefix']}{$this->value}");
            $version = $this->versions[  count($this->versions)-1  ];
            $lastUrl = Common::plain("{$this->urlRoot}{$version['prefix']}{$this->value}");
            
            $html .= "<div><a href='{$lastUrl}' target='_blank'><img src='{$firstUrl}' title='{$title}'></a></div>";
        }        
        
        return $html;
    }
    
    function storeFile($tempName, $originalName) {
        if(preg_match('/  \. ([a-z0-9]{1,7})  $  /xi', $originalName, $m)) {
            $ext = '.'.strtolower($m[1]);            
        }
        else {
            $ext = '.dat';
        }                        
        $storeName = md5(mt_rand()).$ext;

        foreach($this->versions as $version) {
            copy($tempName, "{$this->docRoot}{$version['prefix']}{$storeName}");    
            $this->copyBoundedImage($tempName, "{$this->docRoot}{$version['prefix']}{$storeName}", $version['width'], $version['height']);
        }
        
        return $storeName;
    }    
    
    protected function deleteFiles() {         
        if($this->value != null) {
            foreach($this->versions as $version) {
                @unlink("{$this->docRoot}{$version['prefix']}{$this->value}");
            }
        }
    }  
    
 

    protected function copyBoundedImage($source_file, $destination_file, $bound_w=0, $bound_h=0) {
        $file_ext = strtolower(substr(strrchr($destination_file, "."),1));
        list($src_w, $src_h) = GetImageSize($source_file);

        // Changing image dimensions appropriate to bounds
        list($dest_w, $dest_h) = $this->inscribeBox($src_w, $src_h, $bound_w, $bound_h);

        // Dimensions not changed
        if(($dest_w==$src_w) && ($dest_h==$src_h)) {
            copy($source_file, $destination_file);
        }
        // Dimensions changed
        else {
            if(($file_ext=="jpg") || ($file_ext=="jpeg")) {
                $src_img = ImageCreateFromJPEG($source_file);
                if($src_img === false) throw new Exception("Can't open JPEG");

                $dest_img = ImageCreateTrueColor($dest_w, $dest_h);
                ImageCopyResampled($dest_img, $src_img, 0, 0, 0, 0, $dest_w, $dest_h, $src_w, $src_h);
                ImageJpeg($dest_img, $destination_file);

            }
            else if(($file_ext=="gif")) {
                $src_img = ImageCreateFromGIF($source_file);
                if($src_img === false) throw new Exception("Can't open GIF");

                $dest_img = ImageCreateTrueColor($dest_w, $dest_h);
                ImageCopyResampled($dest_img, $src_img, 0, 0, 0, 0, $dest_w, $dest_h, $src_w, $src_h);
                ImagePNG($dest_img, $destination_file);
            }
            else if(($file_ext=="png")) {
                $src_img = ImageCreateFromPNG($source_file);
                if($src_img === false) throw new Exception("Can't open PNG");
                
                $dest_img = ImageCreateTrueColor($dest_w, $dest_h);
                ImageCopyResampled($dest_img, $src_img, 0, 0, 0, 0, $dest_w, $dest_h, $src_w, $src_h);
                ImagePNG($dest_img, $destination_file);                
            }
        }
    }    
    
   protected function inscribeBox($src_w, $src_h, $bound_w, $bound_h) {
        $dest_w = $src_w;
        $dest_h = $src_h;

        if(($bound_w != null) && ($bound_h != null)) {
            $overlap_w = $src_w - $bound_w;
            $overlap_h = $src_h - $bound_h;
            if(($overlap_w>0) || ($overlap_h>0)) {
                $src_ratio = $src_w / $src_h;

                $scale_w = $bound_w / $src_w;
                $scale_h = $bound_h / $src_h;
                if($scale_h > $scale_w) {
                    $dest_w = $bound_w;
                    $dest_h = $bound_w / $src_ratio;
                }
                else {
                    $dest_h = $bound_h;
                    $dest_w = $bound_h * $src_ratio;
                }
            }
        }

        $dest_h = round($dest_h);
        $dest_w = round($dest_w);

        return array($dest_w, $dest_h);
    }        
}

